#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:liang futing
#@Time :2019/4/9 9:00

from django.conf import settings

def init_permission(current_user,request):
    permission_queryset=current_user.roles.filter(permissions__isnull=False).values(
        'permissions__id','permissions__title','permissions__name','permissions__url','permissions__menu__id',
        'permissions__menu__title','permissions__menu__icon',
        'permissions__pid','permissions__pid__title','permissions__pid__url'
    ).distinct()
    # print(permission_queryset)
    permission_dict={}
    menu_dict={}
    for item in permission_queryset:
        permission_dict[item['permissions__name']]={'id':item['permissions__id'],
                                'title':item['permissions__title'],
                                'url':item['permissions__url'],
                                'pid':item['permissions__pid'],
                                'p_title':item['permissions__pid__title'],
                                'p_url':item['permissions__pid__url']
        }
        menu_id=item['permissions__menu__id']
        if not menu_id:
            continue
        node={'id':item['permissions__id'],'title':item['permissions__title'],'url':item['permissions__url']}

        if menu_id in menu_dict:
            menu_dict[menu_id]['children'].append(node)
        else:
            menu_dict[menu_id] = {
                'id': item['permissions__id'],
                'title': item['permissions__menu__title'],
                'icon': item['permissions__menu__icon'],
                'children': [node,]
            }
    # print(menu_dict)
    # print(permission_dict)
    request.session[settings.PERMISSION_SESSION_KEY]=permission_dict
    request.session[settings.MENU_SESSION_KEY] = menu_dict
